<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Api\Controller;

use Think\Controller;

/**
 * 用户控制器
 * 包括用户中心，用户登录及注册
 */
class UserController extends Controller {

    /*
     * 通过用户openid注册
     */
    public function register_by_openid ()
    {
        $openid = I('openid');
        $wxInfo = I('globalData');
        $wxInfo = $this->object_to_array(json_decode(htmlspecialchars_decode($wxInfo)));
        $name 	= I('name');
        $tel 	= I('tel');
        $school	= I('school');
        $num 	= I('num');
        $enter_year = I('enter_year');
        if (!$openid || $openid == 'undefined') {
            $this->ajaxReturn(['success' => false, 'is_register' => false, 'data' => 'no openid']);
        } else if (empty($wxInfo) || $wxInfo == 'undefined') {
            $this->ajaxReturn(['success' => false, 'is_register' => false, 'data' => 'no exInfo']);
        } else if (!$name || $name == 'undefined') {
            $this->ajaxReturn(['success' => false, 'is_register' => false, 'data' => 'no name']);
        } else if (!$tel || $tel == 'undefined') {
            $this->ajaxReturn(['success' => false, 'is_register' => false, 'data' => 'no tel']);
        } else if (!$school || $school == 'undefined') {
            $this->ajaxReturn(['success' => false, 'is_register' => false, 'data' => 'no school']);
        } else if (!$num || $num == 'undefined') {
            $this->ajaxReturn(['success' => false, 'is_register' => false, 'data' => 'no num']);
        } else if (!$enter_year || $enter_year == 'undefined') {
            $this->ajaxReturn(['success' => false, 'is_register' => false, 'data' => 'no enter_year']);
        }
        $gmt = time();
        $STUDENT = M('student');
        $exist	 = $STUDENT->where(array('openid'=>$openid))->find();
        if (empty($exist)) {
			$uid = $STUDENT->add(array('openid'=>$openid, 'name'=>$name, 'tel'=>$tel, 'school'=>$school, 'number'=>$num, 'enter_year'=>$enter_year, 'sex'=>$wxInfo['gender'], 'head_img'=>$wxInfo['avatarUrl'], 'status'=>'1', 'gmt_create'=>$gmt, 'gmt_modified'=>$gmt));
			if (!empty($uid)) {
				M('weixin')->add(array('openid'=>$openid, 'uid'=>$uid, 'type'=>'1', 'nickname'=>$wxInfo['nickName'], 'gender'=>$wxInfo['gender'], 'country'=>$wxInfo['country'], 'province'=>$wxInfo['province'], 'city'=>$wxInfo['city'], 'avatar'=>$wxInfo['avatarUrl'], 'status'=>'1', 'gmt_create'=>$gmt, 'gmt_modified'=>$gmt));
		        $this->ajaxReturn(['success' => true, 'is_register' => true, 'data' => '注册成功']);
			} else {
		        $this->ajaxReturn(['success' => false, 'is_register' => false, 'data' => 'student表写入失败']);
			}
	    } else {
	        $this->ajaxReturn(['success' => false, 'is_register' => true, 'data' => '用户已注册']);
	    }
        
    }
    private function object_to_array($obj) {
	    $obj = (array)$obj;
	    foreach ($obj as $k => $v) {
	        if (gettype($v) == 'resource') {
	            return;
	        }
	        if (gettype($v) == 'object' || gettype($v) == 'array') {
	            $obj[$k] = (array)object_to_array($v);
	        }
	    }
	 
	    return $obj;
	}
	/**
	 * 陈伟昌 2018-8-29 10:40:54
	 * 通过openid获取个人数据
	 */
	public function getInfo($openid){
		$this->ajaxReturn(D('My','Logic')->info());
	}
	/**
	 * 陈伟昌 2018-8-29 14:34:45
	 * 通过openid更新个人数据
	 */
	public function updateInfo(){
		$changeWhat = I('change');
		$openid = I('openid');
		$value = I('value');
		if ($openid == '' || $changeWhat == '' || $value == '') {
			$this->ajaxReturn(['success' => false, 'msg' => '参数错误，不能为空']);
		}
		$USERINFO = M('student');
		$info = $USERINFO->where(array('openid' => $openid))->find();
		if (empty($info)) {
			$this->ajaxReturn(['success' => false, 'msg' => '没有找到该用户']);
		} else if (!($changeWhat == 'name' || $changeWhat == 'tel' || $changeWhat == 'school' || $changeWhat == 'number' || $changeWhat == 'enter_year' || $changeWhat == 'sex' )){
			$this->ajaxReturn(['success' => false, 'msg' => '参数错误，不在可修改项中，可修改项：openid、name、tel、school、number、enter_year、sex']);
		} else {
			$info[$changeWhat] = $value;
			$info['gmt_create'] = time();
			$USERINFO->save($info);
			$this->ajaxReturn(['success' => true, 'msg' => '修改成功']);
		}
	}
	/**
	 * 陈伟昌 2018-9-1 18:30:29
	 * 通过openid更新个人数据
	 */
	public function createCourse(){
		$appid = I('appid');
		$courseName = I('courseName');
		$questionSet = I('questionSet');
		$creater = I('creater');
		$APPINFO = M('appInfo');
		$COURSE = M('course');
		$TEACHER = M('teacher');
		$QUESTION = M('question');
		$gmt = time();
		$details = $APPINFO->where(array('appid'=>$appid))->find();
		if ($details == null) {
			echo "未找到该appid，请检查";
			die;
		} else if($details['courseId'] != NULL){
			echo "已创建过课程，课程号：";
			echo $details['courseId'];
			die;
		}
		if ($courseName == '' || $questionSet == '' || $creater == '') {
			echo "参数错误，请检查";
			die;
		}
		$teacherData['name'] = $creater;
		$teacherData['school'] = '';
		$teacherData['tel'] = '0';
		$teacherData['status'] = '1';
		$teacherData['gmt_create'] = $gmt;
		$teacherData['gmt_modified'] = $gmt;
		$tid = $TEACHER->add($teacherData);

		$courseData['uid'] = $tid;
		$courseData['name'] = $courseName;
		$courseData['class_name'] = $courseName;
		$courseData['logo'] = '';
		$courseData['remark'] = '';
		$courseData['count'] = 0;
		$courseData['status'] = '1';
		$courseData['gmt_create'] = $gmt;
		$courseData['gmt_modified'] = $gmt;
		$cid = $COURSE->add($courseData);

		$courseSet['cid'] = $cid;
		$courseSet['set_id'] = $questionSet;
		$courseSet['status'] = '1';
		$courseSet['gmt_create'] = $gmt;
		$courseSet['gmt_modified'] = $gmt;
		$QUESTION->add($courseSet);

		$details['courseId'] = $cid ;
		$result = $APPINFO->save($details);
		echo "课程号创建成功，课程号：";
		echo $cid;
		die;
	}
	/**
	 * 陈伟昌 2018-9-2 12:27:33
	 * 通过openid加入课程
	 */
	public function addCourse(){
        $course_id = intval(I('courseId'));
        $openid = I('openid');
        $uid = M('student')->where(array('openid'=>$openid))->field('id')->find();
        $uid = $uid['id'];
        if (!$course_id || !$uid ) {
			$this->ajaxReturn(['success' => false, 'msg' => '参数不能为空']);
        }
        $courseService = new \Api\Service\CourseService();
        $course_add_result = $courseService->add($uid, $course_id);
        if ($course_add_result['success'] === FALSE) {
			$this->ajaxReturn(['success' => false, 'msg' => $course_add_result['message']]);
        }
			$this->ajaxReturn(['success' => true, 'msg' => $course_id]);
	}
	/**
	 * 陈伟昌 2018-9-2 12:34:39
	 * 通过openid获取已加入的课程
	 */
	public function getAddedCourse(){
        $openid = I('openid');
        if (empty($openid)) {
			$this->ajaxReturn(['success' => false, 'msg' => '参数不能为空']);
        }
        $uid = M('student')->where(array('openid'=>$openid))->field('id')->find();
        $list = M('class')->where(array('uid'=>$uid['id']))->field('cid')->find();
        if (empty($list)) {
			$this->ajaxReturn(['success' => false, 'msg' => '无记录']);
        } else {
			$this->ajaxReturn(['success' => true, 'msg' => $list['cid']]);
        }  
	}
	/**
	 * 陈伟昌 2018-9-2 13:45:47
	 * 获取课程信息
	 */
	public function getCourseInfo(){
        $course_id = intval(I('courseId'));
        $info = M('course')->where(array('id'=>$course_id))->find();
        $data = array(
        	'id' => $course_id,
        	'name' => $info['class_name'],
        	'logo' => $info['logo'], 
        	'count' => $info['count'], 
        	'teacher' => ['name' => ''],
        );
        $Tname = M('teacher')->where(array('id'=>$info['uid']))->find();
        $data['teacher']['name'] = $Tname['name'];
		$this->ajaxReturn(['success' => true, 'msg' => $data]);
    }
	/**
	 * 陈伟昌 2018-9-27 17:02:28
	 * 获取课程信息
	 */
	public function getDoneQuesCount(){
        $course_id = intval(I('courseId'));
        $openid = I('openid');
        if (empty($openid)) {
			$this->ajaxReturn(['success' => false, 'msg' => 'openid不能为空']);
        } else if (empty($course_id)) {
			$this->ajaxReturn(['success' => false, 'msg' => 'courseId不能为空']);
        }

        $student_id = M('student')->where(array('openid'=>$openid))->field('id')->find();
        $data = M('QuestionRecord')->where(array('cid'=>$course_id,'uid'=>$student_id['id']))->count();
		$this->ajaxReturn(['success' => true, 'msg' => $data]);
    }
    /*
     * 获取当前课程
     */
    public function current ()
    {
    	$openid = I('openid');
    	$uid = M('Student')->where(['openid' => $openid])->field('id')->find();
    	$user_type = '2';
        $current_course_id = intval(I('current_course_id'));
        $courseService = D('Course','Service');
        $course_item_result = $courseService->get_current_course($uid['id'], $user_type, $current_course_id);
        if ($course_item_result['success'] === FALSE) {
        	$this->ajaxReturn(['success' => FALSE, 'message' => '失败', 'data' => $course_item_result['message'], 'is_openid' => get_openid() ? TRUE : FALSE]);
        }
        $course_item = $course_item_result['data'];
        $course_count = $course_count = D('Class')->countClassByUid($uid);
        $course_count = $course_count ? $course_count : 0;
        $course_item['course_count'] = $course_count;
        $this->ajaxReturn(['success' => TRUE, 'message' => '成功', 'data' => $course_item, 'is_openid' => get_openid() ? TRUE : FALSE]);
    }
	public function stuSearch(){
		$name = I('name');
        $num = intval(I('num'));
        $data = [];
        $isImported = M('importedStu');
        $data['result'] = $isImported -> where(['name' => $name,'num' => $num])->select();
        if (!empty($data['result'])) {
            // 数据存在，返回成功的信息
            return ['status' => 'success', 'message' => '数据获取成功', 'data' => $data['result']];
        } else {
            // 数据不存在，返回失败的信息
            return ['status' => 'failure', 'message' => '没有找到匹配的数据'];
        }
	}
}

